// import { defineVNode } from '@/helpers'
import Modal from './Modal.vue'
import _ from 'lodash-es'
import { createVNode, render } from 'vue'

let _appContext

export function defineVNode(component, vnodeOptions = {}, vNodeProps) {
  let _container

  if (_.isElement(vnodeOptions.container)) {
    _container = vnodeOptions.container
  } else if (_.isString(vnodeOptions.container)) {
    _container = document.getElementById(vnodeOptions.container)
  } else {
    _container = document.body
  }

  const vnode = createVNode(component, vNodeProps)

  vnode.appContext = _appContext
  try {
    render(vnode, _container)
  } catch (error) {
    console.log(error)
  }

  return {
    component: vnode,
    expose: vnode.component?.exposed
  }
}

export async function useModal(contentComponent, props = {}) {
  let instance = {}

  const { result, values } = await new Promise(resolve => {
    const { expose } = defineVNode(
      Modal,
      {
        container: props.target || document.body
      },
      {
        ...props,
        content: contentComponent,
        resolve
      }
    )

    instance = expose
    instance.openModal()
  })

  return {
    instance,
    result,
    values
  }
}
